/**
 * 持久化 Vuex 状态到本地缓存
 */
export default function createPersistedState(options = {}) {
    const key = options.key || 'vuex'
    const paths = options.paths || [] // 支持 ['user', 'settings'] 或 ['user.token']

    // 工具：从 state 中提取指定路径的对象
    function extractStateByPaths(state, paths) {
        const result = {}

        paths.forEach(path => {
            const keys = path.split('.')
            let val = state
            let valid = true

            for (const key of keys) {
                if (val && typeof val === 'object') {
                    val = val[key]
                } else {
                    valid = false
                    break
                }
            }

            if (!valid) return

            // 构建嵌套对象
            keys.reduce((acc, key, idx) => {
                if (idx === keys.length - 1) {
                    acc[key] = val
                } else {
                    acc[key] = acc[key] || {}
                }
                return acc[key]
            }, result)
        })

        return result
    }

    return store => {
        // ✅ 初始化：合并缓存中的状态
        const stored = uni.getStorageSync(key)
        if (stored) {
            const partial = extractStateByPaths(stored, paths)
            store.replaceState(Object.assign({}, store.state, partial))
        }

        // ✅ 每次 mutation 后：写入指定字段
        store.subscribe((mutation, state) => {
            const partial = extractStateByPaths(state, paths)
            uni.setStorageSync(key, partial)
        })
    }
}
